package com.iot;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

/**
 *
 * @author cjm
 * @date 2024/2/23 21:37
 */
public class Test {

    public static void main(String[] args) {
        String broker = "wss://s.sportnanoapi.com:443";

        // 用户名
        String username = "szsmty";
        // 密钥
        String password = "c561259f6722a667f3938ae99019b4f3";

        // 足球比赛主题
        String footballTopic = "sports/football/match.v5";
        // 篮球比赛主题
        String basketballTopic = "sports/basketball/match.v5";

        // LOL比赛主题
        String lolTopic = "";
        // DOTA2比赛主题
        String dota2Topic = "";
        // CS:GO比赛主题
        String csgoTopic = "";
        // KOG比赛主题
        String kogTopic = "";

        // clinetId
        String clientId = "MqttClient_"+String.valueOf(System.currentTimeMillis());
        int qos = 1;
        MemoryPersistence persistence = new MemoryPersistence();

        try {
            MqttClient client = new MqttClient(broker, clientId, persistence);
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setCleanSession(true);
            connOpts.setUserName(username);
            connOpts.setPassword(password.toCharArray());
            connOpts.setConnectionTimeout(10);
            connOpts.setKeepAliveInterval(20);
            // 连接回调
            client.setCallback(new MqttCallback() {
                // 连接失败会有回调
                public void connectionLost(Throwable cause) {
                    System.out.println("connectionLost:" + cause);
                }
                // 连接成功没有回调，但是会收到订阅的消息
                public void messageArrived(String topic, MqttMessage message) {
                    System.out.println("messageArrived:topic" + topic + "--message:" + message.getPayload());
                }

                public void deliveryComplete(IMqttDeliveryToken deliveryComplete) {
                    System.out.println("deliveryComplete:" + deliveryComplete);
                }
            });
            // 连接
            client.connect(connOpts);
            // 有多个主题，可依次订阅
            client.subscribe(footballTopic, qos);
            client.subscribe(basketballTopic, qos);
//      client.subscribe(lolTopic, qos);
//      client.subscribe(dota2Topic, qos);
//      client.subscribe(csgoTopic, qos);
//      client.subscribe(kogTopic, qos);

        } catch (MqttException e) {
            e.printStackTrace();
            System.out.println("connectException:" + e);
            System.out.println("账户验证失败,请确认用户名、密码、授权ip是否正确,否则会认证失败");
        }

    }
}
